<template>
    <el-dialog class="export_preview_dialog my-pdf" :title="dialogOption.title"
               :visible.sync="dialogOption.visible"
               :width="dialogOption.width" :append-to-body="dialogOption.appendToBody"
               :before-close="dialogOption.handleClose" v-dialogDrag>
        <div class="preview_content">
            <iframe class="preview_iframe" :src="iframe_src" allowfullscreen="true"
                    frameborder="0" ref="preview_iframe" :style="iframeStyle"/>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogOption.visible = false">关 闭</el-button>
            <el-button type="primary" @click="handleDownloadPdf" v-if="dialogOption.showPdf">导出PDF</el-button>
            <el-button type="primary" @click="handleDownloadExcel">导出Excel</el-button>
        </div>
    </el-dialog>
</template>

<script>
    import common from "@common/api/common";
    import fileApi from "@common/api/fileApi";

    export default {
        name: "ExportPreview",
        data () {
            return {
                fileApiUrl: fileApi.url,
                preview_url: window.configs.viewPrefix,
                iframe_src: '',
                token: this.$store.state.accessToken.token,
                account_set_sid:this.$utils.getAccountSetSid(),
                defaultOption: {
                    visible: false,
                    title: '导出预览',
                    width: `${$(window).width() * 0.6 + 40}px`,
                    appendToBody: false,
                    handleClose (done) {
                        done();
                    },
                    showPdf: false,
                },
                dialogOption: {
                    visible: false,
                },
            };
        },
        computed: {
            iframeStyle () {
                let width = $(window).width() * 0.6;
                let height = $(window).height() * 0.6 - 100;
                return {
                    // width: `${width}px`,
                    // height: `${height}px`,
                     width:`100%`,
                    height: `100%`,
                };
            },
        },
        methods: {
            showDialog (option) {
                let _this = this;
                if (option) {
                    let filterList = (option.list || []).filter(item => item.biz_type === 'pdf');
                    let showPdf = false;
                    if (!_this.$utils.isNotEmptyList(filterList)) {
                        filterList = (option.list || []).filter(item => item.biz_type === 'excel');
                    } else {
                        showPdf = true;
                    }
                    if (_this.$utils.isNotEmptyList(filterList)) {
                        _this.initIframe(filterList[0]).then(() => {
                            _this.dialogOption = $.extend({}, _this.defaultOption, option, {
                                visible: true,
                                showPdf,
                            });
                        });
                    }
                }
            },
            closeDialog () {
                let _this = this;
                _this.dialogOption = $.extend({}, _this.dialogOption, {
                    visible: false,
                });
            },
            getFileType (fileName) {
                if (this.$utils.isNotEmpty(fileName)) {
                    let index = fileName.lastIndexOf('.');
                    if (index > -1) {
                        return fileName.substring(index + 1, fileName.length);
                    }
                }
            },
            initIframe (item) {
                let _this = this;
                return new Promise(resolve => {
                    let fileType = _this.getFileType(item.original_file_name);
                    if (fileType) {
                        let fileUrl = `${_this.fileApiUrl.getFileWithType}${_this.account_set_sid}/${item.sid}.${fileType}`;
                        let iframe_src = `${_this.preview_url}${this.$utils.transFilePreviewUrl(fileUrl)}`;
                        if (fileType.toLowerCase() === 'pdf') {
                            iframe_src = `${iframe_src}&officePreviewType=pdf`;
                        }
                        _this.iframe_src = `${iframe_src}&v=${new Date().getTime()}`;
                    } else {
                        _this.iframe_src = '';
                    }
                    resolve();
                });
            },
            handleDownloadPdf () {
                let _this = this;
                _this.downloadFile('pdf').then(() => {
                    // _this.closeDialog();
                    _this.$emit('export');
                });
            },
            handleDownloadExcel () {
                let _this = this;
                _this.downloadFile('excel').then(() => {
                    // _this.closeDialog();
                    _this.$emit('export');
                });
            },
            downloadFile (type) {
                let _this = this;
                let filter = _this.dialogOption.list.filter(item => item.biz_type === type);
                if (!_this.$utils.isNotEmptyList(filter)) {
                    return;
                }
                let url = `${_this.fileApiUrl.getFile}${_this.account_set_sid}/${filter[0].sid}`;
                return new Promise(resolve => {
                    common.getData(url, arraybuffer => {
                        if (type === 'excel') {
                            _this.downloadExcelFile(arraybuffer, `${_this.dialogOption.outputName}.xlsx`);
                        } else if (type === 'pdf') {
                            _this.downloadPdfFile(arraybuffer, `${_this.dialogOption.outputName}.pdf`);
                        }
                        resolve();
                    });
                });
            },
            downloadExcelFile (arraybuffer, fileName) {
                let _this = this;
                let blob = new Blob([arraybuffer], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
                });
                _this.downloadBlobFile(blob, fileName);
            },
            downloadPdfFile (arraybuffer, fileName) {
                let _this = this;
                let blob = new Blob([arraybuffer], {
                    type: 'application/pdf;charset-UTF-8'
                });
                _this.downloadBlobFile(blob, fileName);
            },
            downloadBlobFile (blob, fileName) {
                let _this = this;
                if (window.navigator.msSaveOrOpenBlob) {
                    navigator.msSaveBlob(blob, fileName);
                    if (_this.$utils.isNotEmpty(_this.dialogOption.sid)) {
                        _this.$emit('download', _this.dialogOption.sid);
                    }
                } else {
                    let link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = fileName;
                    link.click();
                    window.URL.revokeObjectURL(link.href);
                    if (_this.$utils.isNotEmpty(_this.dialogOption.sid)) {
                        _this.$emit('download', _this.dialogOption.sid);
                    }
                }
            },
        },
    }
</script>

<style>
    .export_preview_dialog .preview_content {
        min-height: 400px;
        height: 100%;
    }

    .export_preview_dialog .preview_content .preview_iframe {
        width: 100%;
        height: 100%;
    }
</style>
